import { h } from "koishi"

export const name = "onebot-json-to-url"

export function apply(ctx) {
  ctx = ctx.platform("onebot")

  ctx.middleware((session, next) => {
    if (h.select(session.elements, "json").length) {
      session.elements = h.transform(session.elements, {
        json(attrs, children) {
          try {
            const data = JSON.parse(attrs.data)
            const url = data?.meta?.detail_1?.qqdocurl
              || data?.meta && Object.values(data.meta).find(p => p?.jumpUrl)?.jumpUrl
            if (url) {
              ctx.logger.debug([data?.prompt, url])
              return h("json", attrs, [h("a", { href: url }, data?.prompt || url)])
            }
          } catch (e) { ctx.logger.error(e) }
          return h("json", attrs, children)
        },
      })
    }
    return next()
  }, true)

  ctx.inject(["autoDeleteResponse"], ctx => {
    ctx.middleware((session, next) => {
      if (session.elements[0]?.type === "json") try {
        const data = JSON.parse(session.elements[0].attrs.data)
        const url = data?.meta?.music?.musicUrl
        if (url) return next(async () => {
          ctx.autoDeleteResponse.send(session, [h.quote(session.messageId), h.text(url)])
        })
      } catch {}
      return next()
    })
  })
}
